package com.alogic.vfs.xscript;

import com.alogic.vfs.core.VirtualFileSystem;
import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;


/**
 * 生成文件的md5码
 *
 * @since  1.6.13.37 [20200223 duanyy] <br>
 */
public class FileMd5 extends AbstractLogiclet {
    protected String pid = "$vfs";
    protected String $path = "/newfile";
    protected String id = "$vfs-md5";

    public FileMd5(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        pid = PropertiesConstants.getString(p,"pid",pid,true);
        id = PropertiesConstants.getString(p,"id",id,true);
        $path = PropertiesConstants.getRaw(p,"path",$path);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx,
                             ExecuteWatcher watcher) {
        VirtualFileSystem vfs = ctx.getObject(pid);
        if (vfs == null){
            throw new BaseException("core.e1001",String.format("Can not find vfs:%s", pid));
        }

        String path = PropertiesConstants.transform(ctx,$path,"");
        if (StringUtils.isNotEmpty(path)){
            String md5 = vfs.getFileDigest(path);
            if (StringUtils.isNotEmpty(md5)){
                ctx.SetValue(id,md5);
            }
        }

    }
}
